﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
using System.Configuration;

namespace AssettDatabase
{
    public partial class Form_Add_Assett : Form
    {
        public int retAsset_ID { get; set; } 
        public Form_Add_Assett()
        {
            InitializeComponent();
        }

        private void Btn_Return_Main_Click(object sender, EventArgs e)
        {
            this.Dispose();
            FormProvider.MainMenu.Show();
        }

        void fill_Asset_Type()
        {
            try
            {
                BLL.Asset_Type bllAsset_Type = new BLL.Asset_Type();
                List<VO.Asset_Type> voAsset_TypeList;
                voAsset_TypeList = bllAsset_Type.GetAsset_Type();

                AA_CB_Assett_Type.DataSource = voAsset_TypeList;
                AA_CB_Assett_Type.DisplayMember = VO.Asset_Type.Asset_Type_Fields.Asset_Type_Name.ToString();
                AA_CB_Assett_Type.ValueMember = VO.Asset_Type.Asset_Type_Fields.Asset_Type_ID.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }                        
        }

        void fill_Vendor()
        {
            try
            {
                BLL.Vendor bllVendor = new BLL.Vendor();
                List<VO.Vendor> voVendorList;
                voVendorList = bllVendor.GetVendor();

                AA_CB_Vendor_Name.DataSource = voVendorList;
                AA_CB_Vendor_Name.DisplayMember = VO.Vendor.Vendor_Fields.Vendor_Name.ToString();
                AA_CB_Vendor_Name.ValueMember = VO.Vendor.Vendor_Fields.Vendor_ID.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void fill_Supplier()
        {
            try
            {
                BLL.Supplier bllSupplier = new BLL.Supplier();
                List<VO.Supplier> voSupplierList;
                voSupplierList = bllSupplier.GetSupplier();

                AA_CB_Supplier.DataSource = voSupplierList;
                AA_CB_Supplier.DisplayMember = VO.Supplier.Supplier_Fields.Supplier_Name.ToString();
                AA_CB_Supplier.ValueMember = VO.Supplier.Supplier_Fields.Supplier_ID.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }   

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void AA_TB_Customer_Name_TextChanged(object sender, EventArgs e)
        {

        }
        private void Form_Add_Assett_Load(object sender, EventArgs e)
        {
            AutoCompleteText();
            fill_Asset_Type();
            fill_Vendor();
            fill_Supplier();
            Load_AssetData();
        }

        private void Load_AssetData()
        {
            if (retAsset_ID != 0)
            {
                BT_Create_Assett.Text = "Modify Asset";
                //BT_Create_Assett.Enabled = false;

                BLL.Asset bllAsset = new BLL.Asset();
                List<VO.Asset> voAssetList;
                voAssetList = bllAsset.GetAssetById(retAsset_ID);

                foreach (VO.Asset asset in voAssetList)
                {
                    AA_TB_Customer_Name.Text = asset.Customer_Name;
                    AA_TB_InvoiceNumber.Text = asset.A_S_Invoice_Number;
                    AA_TB_ModelNumber.Text = asset.Model_Number;
                    AA_TB_Notes.Text = asset.Asset_Notes;
                    AA_TB_RT_Customer_ID.Text = asset.Customer_ID.ToString();
                    AA_TB_SerialNumber.Text = asset.Serial_Number;
                    AA_TB_SupplierInvoiceNumber.Text = asset.Supplier_Invoice_Number;
                    AA_CB_Assett_Type.SelectedValue = asset.Asset_Type_ID;
                    AA_CB_Supplier.SelectedValue = asset.Supplier_ID;
                    //AA_CB_Vendor_Name.SelectedValue = asset.Vendor_Name;
                    AA_Date_Purchase_Date.Text = asset.A_S_Purchase_Date.ToString();
                    AA_Date_Software_Renewal.Text = asset.Software_Renewal_Date.ToString();
                    AA_Date_Sold_to_Customer.Text = asset.Sold_To_Customer_Date.ToString();
                    AA_Date_Warranty_Expiry.Text = asset.Warranty_Expiry.ToString();
                    chk_Add_Stock.Checked = Convert.ToBoolean(asset.Asset_InStock);

                    if (asset.Asset_Image.Count > 0)
                    {
                        ImageList imglist = new ImageList();
                        imglist.ImageSize = new Size(64, 64);
                        string fullPath = ConfigurationManager.AppSettings["FilePath"].ToString();
                        foreach (VO.Asset_Image asset_image in asset.Asset_Image)
                        {
                            Image image = Image.FromFile(Path.Combine(fullPath, retAsset_ID.ToString(), asset_image.FileName));
                            Image mImage = new Bitmap(image);
                            image.Dispose();
                            imglist.Images.Add(Path.Combine(fullPath, retAsset_ID.ToString(), asset_image.FileName), mImage);
                        }

                        lstImages.View = View.LargeIcon;
                        lstImages.LargeImageList = imglist;
                        foreach (string key in imglist.Images.Keys)
                        {
                            ListViewItem item = new ListViewItem();
                            item.ImageIndex = imglist.Images.IndexOfKey(key);
                            item.Text = Path.GetFileName(key);
                            item.Tag = key;
                            lstImages.Items.Add(item);
                        }
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void AA_BT_Add_Assett_Type_Click(object sender, EventArgs e)
        {
            
            Form_Add_Asset_Type f12 = new Form_Add_Asset_Type();
            f12.ShowDialog();
        }

        private void AA_CB_Assett_Type_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void AA_BT_Add_Vendor_Click(object sender, EventArgs e)
        {
            Form_Add_Vendor f13 = new Form_Add_Vendor();
            f13.ShowDialog();
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {

        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void AA_RB_Warranty_No_CheckedChanged(object sender, EventArgs e)
        {
            AA_Date_Warranty_Expiry.Enabled = false;
        }

        private void AA_RB_Warranty_Yes_CheckedChanged(object sender, EventArgs e)
        {
            AA_Date_Warranty_Expiry.Enabled = true;
        }

        private void radioButton4_CheckedChanged(object sender, EventArgs e)
        {
            AA_Date_Software_Renewal.Enabled = true;
        }

        private void AA_RB_Software_Maintainance_No_CheckedChanged(object sender, EventArgs e)
        {
            AA_Date_Software_Renewal.Enabled = false;
        }

        private void AA_BT_Search_Customer_Click(object sender, EventArgs e)
        {
            using (var form = new Form_Sel_Customer())
            {
                var result = form.ShowDialog();
                if (result == DialogResult.OK)
                {
                    Customer_Search(form.retCustomer_ID);
                }
            }
        }

        private void Form_Add_Assett_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Dispose();
            FormProvider.MainMenu.Show();
        }

        private void AA_BT_Add_Image_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Title = "Select Asset Image";
            openFileDialog1.Filter = "Images (png, jpg, bpm, gif)|*.jpeg;*.jpg;*.gif;*.bmp;*.png|Select All (*)|*";
            openFileDialog1.Multiselect = true;
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ImageList imglist = new ImageList();

                imglist.ImageSize = new Size(64, 64);
                foreach (string file in openFileDialog1.FileNames)
                {
                    Image image = Image.FromFile(file);
                    Image mImage = new Bitmap(image);
                    image.Dispose();
                    imglist.Images.Add(file, mImage);
                }  

                lstImages.View = View.LargeIcon;
                lstImages.LargeImageList = imglist;
                foreach (string key in imglist.Images.Keys)
                {
                    ListViewItem item = new ListViewItem();
                    item.ImageIndex = imglist.Images.IndexOfKey(key);
                    item.Text = Path.GetFileName(key);
                    item.Tag = key;
                    lstImages.Items.Add(item);
                }
            }
        }

        private void BT_Create_Assett_Click(object sender, EventArgs e)
        {
            try
            {
                if (AA_TB_RT_Customer_ID.Text.Length == 0)
                {
                    MessageBox.Show("Customer is a mandatory field.");
                    return;
                }
                if (AA_TB_SerialNumber.Text.Length == 0)
                {
                    MessageBox.Show("Serial Number is a mandatory field.");
                    return;
                }
                if (AA_TB_ModelNumber.Text.Length == 0)
                {
                    MessageBox.Show("Model Number is a mandatory field.");
                    return;
                }
                if (AA_CB_Assett_Type.SelectedIndex == -1)
                {
                    MessageBox.Show("Asset Type is a mandatory field.");
                    return;
                }
                if (AA_CB_Vendor_Name.SelectedIndex == -1)
                {
                    MessageBox.Show("Vendor is a mandatory field.");
                    return;
                }
                if (AA_Date_Purchase_Date.Text.Length == 0)
                {
                    MessageBox.Show("A&S Tech Purchase Date is a mandatory field.");
                    return;
                }
                if (AA_CB_Supplier.SelectedIndex == -1)
                {
                    MessageBox.Show("Purchased From is a mandatory field.");
                    return;
                }

                long resAsset_Add = -1;
                BLL.Asset bllAsset = new BLL.Asset();
                List<VO.Asset_Image> imageList = new List<VO.Asset_Image>();
                foreach (ListViewItem item in lstImages.Items)
                {
                    imageList.Add(new VO.Asset_Image() { FileName = item.Text });
                }

                if (retAsset_ID > 0)
                {
                    if (!bllAsset.Update(Convert.ToInt32(AA_TB_RT_Customer_ID.Text), AA_TB_SerialNumber.Text, AA_TB_ModelNumber.Text, Convert.ToInt32(AA_CB_Assett_Type.SelectedValue), AA_CB_Vendor_Name.Text,
                                    Convert.ToDateTime(AA_Date_Purchase_Date.Text), Convert.ToDateTime(AA_Date_Sold_to_Customer.Text), AA_TB_InvoiceNumber.Text, Convert.ToInt32(AA_CB_Supplier.SelectedValue),
                                    Convert.ToDateTime(AA_Date_Software_Renewal.Text), Convert.ToDateTime(AA_Date_Warranty_Expiry.Text), AA_TB_SupplierInvoiceNumber.Text, AA_TB_Notes.Text, imageList, Convert.ToInt32(chk_Add_Stock.Checked), retAsset_ID))
                    {
                        MessageBox.Show("An error occurred during asset modification");
                        return;
                    }
                    resAsset_Add = retAsset_ID;
                }
                else
                {
                    resAsset_Add = bllAsset.Add(Convert.ToInt32(AA_TB_RT_Customer_ID.Text), AA_TB_SerialNumber.Text, AA_TB_ModelNumber.Text, Convert.ToInt32(AA_CB_Assett_Type.SelectedValue), AA_CB_Vendor_Name.Text,
                                    Convert.ToDateTime(AA_Date_Purchase_Date.Text), Convert.ToDateTime(AA_Date_Sold_to_Customer.Text), AA_TB_InvoiceNumber.Text, Convert.ToInt32(AA_CB_Supplier.SelectedValue),
                                    Convert.ToDateTime(AA_Date_Software_Renewal.Text), Convert.ToDateTime(AA_Date_Warranty_Expiry.Text), AA_TB_SupplierInvoiceNumber.Text, AA_TB_Notes.Text, imageList, Convert.ToInt32(chk_Add_Stock.Checked));

                    if (resAsset_Add == -1)
                    {
                        MessageBox.Show("An error occurred during asset insert");
                        return;
                    }
                }

                string fullPath = ConfigurationManager.AppSettings["FilePath"].ToString();
                foreach (ListViewItem item in lstImages.Items)
                {
                    if (!Directory.Exists(Path.Combine(fullPath, resAsset_Add.ToString())))
                        Directory.CreateDirectory(Path.Combine(fullPath, resAsset_Add.ToString()));
                    if (!File.Exists(Path.Combine(fullPath, resAsset_Add.ToString(), Path.GetFileName(item.Tag.ToString()))))
                        File.Copy(item.Tag.ToString(), Path.Combine(fullPath, resAsset_Add.ToString(), Path.GetFileName(item.Tag.ToString())), true);
                }

                MessageBox.Show("Asset has been added succesfully");
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void AutoCompleteText()
        {
            try
            {
                BLL.Customer bllCustomer = new BLL.Customer();
                AutoCompleteStringCollection strCollection = new AutoCompleteStringCollection();
                AA_TB_Customer_Name.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                AA_TB_Customer_Name.AutoCompleteSource = AutoCompleteSource.CustomSource;
                AA_TB_Customer_Name.AutoCompleteCustomSource = strCollection;

                List<VO.Customer> voCustomerList = bllCustomer.GetCustomers();

                foreach (VO.Customer customer in voCustomerList)
                {
                    strCollection.Add(customer.Customer_Name);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void AA_TB_Customer_Name_KeyDown(object sender, KeyEventArgs e)
        {
            if (AA_TB_Customer_Name.Text.Length != 0)
                if (e.KeyCode == Keys.Enter)
                {
                    Customer_Search(null);
                }
        }

        private void Customer_Search(string Customer_ID)
        {
            try
            {
                BLL.Customer bllCustomer = new BLL.Customer();
                List<VO.Customer> voCustomerList;
                if (Customer_ID != null)
                    voCustomerList = bllCustomer.GetCustomerById(Customer_ID);
                else
                    voCustomerList = bllCustomer.GetCustomerByName(AA_TB_Customer_Name.Text);

                foreach (VO.Customer customer in voCustomerList)
                {
                    AA_TB_Customer_Name.Text = customer.Customer_Name.ToString();
                    AA_TB_RT_Customer_ID.Text = customer.Customer_ID.ToString();
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void AA_BT_View_Image_Click(object sender, EventArgs e)
        {
            if (lstImages.Items.Count == 0)
            {
                MessageBox.Show("You have to add images first.");
            }
            else
            {
                Form_View_Images frm = new Form_View_Images();
                frm.imgList = lstImages.LargeImageList;
                frm.ShowDialog();
            }
        }

        private void AA_TB_SerialNumber_TextChanged(object sender, EventArgs e)
        {

        }

        private void AA_TB_ModelNumber_TextChanged(object sender, EventArgs e)
        {

        }

        private void chk_Add_Stock_CheckedChanged(object sender, EventArgs e)
        {
            if (chk_Add_Stock.Checked)
            {
                AA_Date_Sold_to_Customer.Enabled = false;
                AA_TB_InvoiceNumber.Enabled = false;
            }
            else
            {
                AA_Date_Sold_to_Customer.Enabled = true;
                AA_TB_InvoiceNumber.Enabled = true;
            }
        }

        private void AA_BT_Del_Image_Click(object sender, EventArgs e)
        {
            if (lstImages.SelectedItems.Count > 0)
            {
                string fullPath = ConfigurationManager.AppSettings["FilePath"].ToString();

                foreach (ListViewItem item in lstImages.SelectedItems)
                {
                    lstImages.Items.Remove(item);
                    if (File.Exists(item.Tag.ToString()) && fullPath == Path.GetDirectoryName(item.Tag.ToString()))
                    {
                        File.Delete(item.Tag.ToString());

                        BLL.Asset bllAsset = new BLL.Asset();
                        bllAsset.Del_Asset_Image(retAsset_ID, Path.GetFileName(item.Tag.ToString()));
                    }
                }   
            }
            else
                MessageBox.Show("Please select the image/s you want to delete!");
        }
    }
}
